package app.persistencia;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import app.utils.Utiles;

public class ListasDeReproduccion {
	
	static private ListasDeReproduccion listasDeReproduccion = null;
	private HashMap<Integer, ListaDeReproduccion> listasDisponibles = null;
	private ListasDeReproduccion(){
		listasDisponibles = new HashMap<Integer, ListaDeReproduccion>();
	};
	
	static public ListasDeReproduccion getIntances() {
		if(listasDeReproduccion == null) {
			listasDeReproduccion = new ListasDeReproduccion();
		}
		return listasDeReproduccion;
	}
	
	public void importListas(Activity context) {
		UsuariosSQLiteHelper dbLists = new UsuariosSQLiteHelper(context,"DBLists", null, 1);
        final SQLiteDatabase db = dbLists.getWritableDatabase();
		Cursor c;
        c = db.rawQuery("Select * from reproductionLists;", null);
        if(c.moveToFirst())
        {
        	do {
        		Integer idList = c.getInt(0);
        		String nameList = c.getString(1);
        		ArrayList<CancionLista> cancionesLista = importarCancionLista(db,idList);
        		ListaDeReproduccion listaR = new ListaDeReproduccion(idList, nameList, cancionesLista);
        		listasDisponibles.put(idList, listaR);
        	}while(c.moveToNext());
        }
        if(db!= null)
        	db.close();
        c.close();
        dbLists.close();
	}
	
	private ArrayList<CancionLista> importarCancionLista(SQLiteDatabase db, Integer idList) {
		ArrayList<CancionLista> cancionesLista = new ArrayList<CancionLista>();
        String[] values = new String[1];
        values[0] = String.valueOf(idList);
        
		Cursor c = db.rawQuery("Select * from songsByList where idList = ? ORDER BY position ASC;",values);
		
		if(c.moveToFirst())
		{
			do {
				String path = c.getString(3);
				int pos = c.getInt(4);
				CancionLista cancionLista = new CancionLista(path, pos); 
				cancionesLista.add(cancionLista);
			}while(c.moveToNext());
		}
		return cancionesLista;
	}

	public HashMap<Integer, ListaDeReproduccion> getListasDisponibles() {
		return listasDisponibles;
	}
	public void addNewLista(Activity context, String name) {
		String command = "INSERT INTO reproductionLists(name)"
 				+ " VALUES ('"+name+"');";
		UsuariosSQLiteHelper dbLists = new UsuariosSQLiteHelper(context,"DBLists", null, 1);
        SQLiteDatabase db = dbLists.getWritableDatabase();

	    db.execSQL(command);
		String[] values = new String[1];
		values[0] = name;
		Cursor c = db.rawQuery("Select id from reproductionLists where name = ?;", values);
		if(c.moveToFirst()) {
			int idL = c.getInt(0);
			System.out.println(idL);
			if(!listasDisponibles.containsKey(idL)){ 
				ListaDeReproduccion lista = new ListaDeReproduccion(idL, name, new ArrayList<CancionLista>());
				listasDisponibles.put(idL, lista);
				System.out.println("Escribir listas:");
				ListasDeReproduccion.getIntances().escribirLista();

			}
			else {
				/**
				 * Reportar Excepcion lista ya existe
				 */
			}
		}
		db.close();
     	dbLists.close();
	}
	public boolean existListWithName(Activity context, String name) {
		UsuariosSQLiteHelper dbLists = new UsuariosSQLiteHelper(context,"DBLists", null, 1);
        SQLiteDatabase db = dbLists.getReadableDatabase();
        String[] values = new String[1];
		values[0] = name;
		Cursor c;
		//System.out.println("hola");
		c = db.rawQuery("Select * from reproductionLists where name = ?;", values);
		//System.out.println("hola3");
		if(c!= null && c.moveToFirst()) {
			//System.out.println("hola2");
			if(db!= null)
				db.close();
			dbLists.close();
			return true;
		}
		if(db!= null)
			db.close();
		dbLists.close();
		return false;
	}
	public void deleteLista(Activity context, Integer id) {
		listasDisponibles.remove(id);
		String[] values = new String[1];
		values[0] = String.valueOf(id);
		//System.out.println(id);
		UsuariosSQLiteHelper dbLists = new UsuariosSQLiteHelper(context,"DBLists", null, 1);
        SQLiteDatabase db = dbLists.getWritableDatabase();
		db.execSQL("DELETE FROM songsByList where idList = ?;", values);	
		db.execSQL("DELETE FROM reproductionLists where id = ?;", values);	
		db.close();
		dbLists.close();
	}
	public ListaDeReproduccion getListaDeReproduccion(Integer id) {
		return listasDisponibles.get(id);
	}
	
	public boolean addSong(Activity context, Integer idLista, String path)
	{
		/**
		 * TODO Modificar para omitir el nombre en la BD.
		 */
		String name = Utiles.getTittle(path);
		int position = listasDisponibles.get(idLista).getLastPosition();
		String command = "INSERT INTO songsByList(idList,name,path,position)"
 				+ "VALUES ("+idLista+",'"+name+"','"+path+"',"+position+");";
		UsuariosSQLiteHelper dbLists = new UsuariosSQLiteHelper(context,"DBLists", null, 1);
        SQLiteDatabase db = dbLists.getWritableDatabase();

		db.execSQL(command);
		db.close();
		CancionLista cancion = new CancionLista(path, position);
		listasDisponibles.get(idLista).addSong(cancion);
		return true;
	}
	public boolean removeSong(Activity context, Integer idLista, String name, Integer pos) {
		
		boolean removed = listasDisponibles.get(idLista).removeSong(name, pos);
		if(removed) {
			String[] values = new String[3];
			values[0] = String.valueOf(idLista);
			values[1] = name;
			values[2] = String.valueOf(pos);
			UsuariosSQLiteHelper dbLists = new UsuariosSQLiteHelper(context,"DBLists", null, 1);
	        SQLiteDatabase db = dbLists.getWritableDatabase();
			db.execSQL("DELETE FROM songsByList where idList = ? and name = ? and position = ?;", values);	
			db.close();
			dbLists.close();
			return true;
		}
		return false;
	}
	@SuppressWarnings("rawtypes")
	public ArrayList<ListaDeReproduccion> getList() {
		Iterator iter = listasDisponibles.entrySet().iterator();
		Map.Entry e;
		ArrayList<ListaDeReproduccion> list = new ArrayList<ListaDeReproduccion>();
		while (iter.hasNext()) {
			e = (Map.Entry)iter.next();
			list.add((ListaDeReproduccion) e.getValue());
		}
		return list;
	}

	public void escribirLista() {
		Iterator iter = listasDisponibles.entrySet().iterator();
		Map.Entry e;
		ArrayList<ListaDeReproduccion> list = new ArrayList<ListaDeReproduccion>();
		while (iter.hasNext()) {
			e = (Map.Entry)iter.next();
			ListaDeReproduccion l = (ListaDeReproduccion) e.getValue();
			System.out.println(l.getId());
		}
	}
	
}
